package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.service.IBizOrderService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.utils.DictUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2020-09-09
 */
@Service
public class BizOrderServiceImpl implements IBizOrderService
{
    @Resource
    private BizOrderMapper bizOrderMapper;

    @Resource
    private BizProductMapper bizProductMapper;

    @Resource
    private BizMemberMapper bizMemberMapper;

    @Resource
    private BizOrderDeliveryServiceImpl bizOrderDeliveryService;

    @Resource
    private BizMemberAddressMapper bizMemberAddressMapper;

    @Resource
    private BizAccountServiceImpl bizAccountService;

    @Resource
    private BizTeamRewardServiceImpl bizTeamRewardService;

    /**
     * 查询订单
     *
     * @param id 订单ID
     * @return 订单
     */
    @Override
    public BizOrder selectBizOrderById(Long id)
    {
        return bizOrderMapper.selectBizOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param bizOrder 订单
     * @return 订单
     */
    @Override
    public List<BizOrder> selectBizOrderList(BizOrder bizOrder)
    {
        return bizOrderMapper.selectBizOrderList(bizOrder);
    }

    /**
     * 新增订单
     *
     * @param bizOrder 订单
     * @return 结果
     */
    @Override
    public int insertBizOrder(BizOrder bizOrder)
    {
        bizOrder.setCreateTime(DateUtils.getNowDate());
        return bizOrderMapper.insertBizOrder(bizOrder);
    }

    /**
     * 修改订单
     *
     * @param bizOrder 订单
     * @return 结果
     */
    @Override
    public int updateBizOrder(BizOrder bizOrder)
    {
        bizOrder.setUpdateTime(DateUtils.getNowDate());
        return bizOrderMapper.updateBizOrder(bizOrder);
    }

    /**
     * 订单发货
     *
     * @param orderID 订单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deliverBizOrder(Long orderID, Integer deliveryNum)
    {
        BizOrder bizOrder = bizOrderMapper.selectBizOrderById(orderID);
        if (bizOrder == null || deliveryNum <= 0) {
            return 0;
        }
        long hasDeliveryNum = bizOrder.getDeliveryNum();
        int total = bizOrder.getProductCount();
        int status = bizOrder.getOrderStatus();
        //校验订单状态
        if (hasDeliveryNum > 0 && status != BizOrder.STATUS_DELIVERING || hasDeliveryNum == 0 && status != BizOrder.STATUS_PAYED) {
            return 0;
        }
        //验证发货数量
        if (hasDeliveryNum + deliveryNum > total) {
            return 0;
        }
        boolean isDeliveryOver = (hasDeliveryNum + deliveryNum == total);
        //插入发货记录
        BizOrderDelivery orderDelivery = new BizOrderDelivery();
        orderDelivery.setOrderId(orderID);
        orderDelivery.setNum(deliveryNum);
        bizOrderDeliveryService.insertBizOrderDelivery(orderDelivery);
        int newStatus = isDeliveryOver ? BizOrder.STATUS_DELIVERY : BizOrder.STATUS_DELIVERING;
        if (status != newStatus) {
            //改变状态
            bizOrder.setOrderStatus(newStatus);
            bizOrder.setUpdateBy(ShiroUtils.getLoginName());
            bizOrder.setUpdateTime(new Date());
            return bizOrderMapper.updateBizOrder(bizOrder);
        }
        return 1;
    }

    /**
     * 删除订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBizOrderByIds(String ids)
    {
        return bizOrderMapper.deleteBizOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单信息
     *
     * @param id 订单ID
     * @return 结果
     */
    @Override
    public int deleteBizOrderById(Long id)
    {
        return bizOrderMapper.deleteBizOrderById(id);
    }

    /**
     * 添加订单
     *
     * @param
     * @return AjaxResult
     */
    @Override
    @Transactional
    public AjaxResult orderAdd(Long memberID, Long productID, int productNum, Long addressID, String remark)
    {
        if (productNum <= 0 || productNum > 99) {    //检测数量
            return AjaxResult.warn("商品数目异常");
        }
        if (!StringUtils.isEmpty(remark) && remark.length() > 30) {    //检测备注
            return AjaxResult.warn("备注信息太长");
        }
        //取出商品
        BizProduct product = bizProductMapper.selectBizProductById(productID);
        if (product == null || product.getOnlineStatus() == 0) {    //检测上架
            return AjaxResult.warn("该商品不存在或已下架");
        }
        //订单总价
        BigDecimal amount = product.getAmount();
        BigDecimal orderTotal = amount.multiply(new BigDecimal(productNum));
        //判断余额
        BizMember member = bizMemberMapper.selectBizMemberById(memberID);
        Long douBalance = member.getDouBalance();
        if (douBalance < orderTotal.longValue()) {
            return AjaxResult.warn("福豆余额不足");
        }
        //判断是否已出局
        BigDecimal cashbackAmount = product.getCashbackAmount();
        BigDecimal cashbackTotalAmount = new BigDecimal(0);
        boolean isTeam = cashbackAmount.longValue() > 0;
        if (isTeam) {       //专项相关判断
            int specialLevel = member.getSpecialLevel();
            if (specialLevel == 0) {
                return AjaxResult.warn("此账号已经出局, 无法继续购买此产品");
            }
            //专项福豆75限制
            int specialLimit = Integer.parseInt(DictUtils.getDictLabel("busi_award_set", "7"));
            //取出购买盒数
            int turnMax = 3;
            int buyNum = (int) bizOrderMapper.selectBuyNum(memberID);
            int buys = buyNum % turnMax;
            if (buys == 0) {    //如果已买整数轮次 判断专项福豆是否小于75
                if (member.getDouSpecial() >= specialLimit) {
                    return AjaxResult.warn("专项福豆尚未返还完毕, 无法继续购买");
                }
            } else if (buys + productNum > turnMax) {
                return AjaxResult.warn("此产品您最多只能再购买" + (turnMax - buys) + "盒");
            }

            //判断专项划拨相关金额
            int decreaseAmount = Integer.parseInt(DictUtils.getDictLabel("busi_award_set", "4"));
            //重新计算专项金额
            cashbackAmount = cashbackAmount.add(new BigDecimal((specialLevel - 1) * decreaseAmount));
            cashbackTotalAmount = cashbackAmount.multiply(new BigDecimal(productNum));
        }

        //判断地址
        BizMemberAddress address = bizMemberAddressMapper.selectBizMemberAddressById(addressID);
        if (address == null || !address.getMemberID().equals(memberID)) {
            return AjaxResult.warn("收货地址不正确");
        }

        //创建订单
        BizOrder order = new BizOrder();
        order.setOrderSn("ORD" + DateUtils.getMilliTime());
        order.setMemberId(memberID);
        order.setMobile(member.getMobile());
        order.setMemberName(member.getMemberName());
        order.setOrderAmount(orderTotal);
        order.setOrderStatus(BizOrder.STATUS_PAYED);    //已支付
        order.setIsTeam(isTeam ? 1 : 0);  //是否团队福豆影响订单
        order.setTeamCount(isTeam ? productNum : 0);    //团队盒数
        order.setRecommendPayed(isTeam ? 1 : 0);    //等待明天结算
        order.setRemark(remark);
        order.setAddressDetail(address.getAddress());
        order.setAddressId(addressID);
        insertBizOrder(order);
        //订单详情
        BizOrderDetail orderDetail = new BizOrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setOrderSn(order.getOrderSn());
        orderDetail.setProductId(productID);
        orderDetail.setProductCode(product.getProductName());
        orderDetail.setProductCount(productNum);
        orderDetail.setProductAmount(amount);
        bizOrderMapper.insertBizOrderDetail(orderDetail);

        String businessCode = String.valueOf(order.getOrderSn());
        //减去福豆余额账户
        boolean result = bizAccountService.accountChange(memberID, BizAccount.DOU_BALANCE, BizAccountDetail.DOU_DETAIL_TYPE_ORDER, -orderTotal.longValue(), businessCode, BizAccountDetail.DOU_DESC_ORDER);
        if (!result) {
            return AjaxResult.warn("扣款失败,请联系管理员");
        }
        //增加专项账户
        if(isTeam) {
            if (cashbackTotalAmount.longValue() > 0) {
                result = bizAccountService.accountChange(memberID, BizAccount.DOU_SPECIAL, BizAccountDetail.DOU_DETAIL_TYPE_CHARGE, cashbackTotalAmount.longValue(), businessCode, BizAccountDetail.DOU_DESC_SPECIAL1);
                if (!result) {
                    return AjaxResult.warn("扣款失败,请联系管理员");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 订单收货
     *
     * @param
     * @return AjaxResult
     */
    @Override
    @Transactional
    public AjaxResult orderConfirm(Long userID, Long orderID)
    {
        BizOrder order = selectBizOrderById(orderID);
        //验证
        if (order == null || !order.getMemberId().equals(userID) || order.getOrderStatus() != BizOrder.STATUS_DELIVERY) {
            return AjaxResult.warn("订单操作失败");
        }
        order.setOrderStatus(BizOrder.STATUS_COMPLETED);
        order.setUpdateBy(String.valueOf(userID));
        updateBizOrder(order);
        return AjaxResult.success();
    }

    /**
     * 查询团队订单
     *
     * @param memberID 会员ID
     * @return 订单集合
     */
    @Override
    public List<Map> selectTeamBizOrder(Long memberID)
    {
        return bizOrderMapper.selectTeamBizOrder(memberID);
    }

    /**
     * 用户购买盒数
     *
     * @param memberID
     * @return 结果
     */
    @Override
    public long selectBuyNum(Long memberID)
    {
        return bizOrderMapper.selectBuyNum(memberID);
    }
}
